package com.hscm.boss.common.exception.handle;

import com.hscm.boss.common.enums.ResponseCode;
import com.hscm.boss.common.exception.BossException;
import com.hscm.boss.mvc.model.AjaxResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

//全局异常处理
@RestControllerAdvice
public class GlobalExceptionHandle {

    //getClass() 得到当前运行的类
    Logger logger = LoggerFactory.getLogger(getClass());

    //处理BossException
    @ExceptionHandler({BossException.class})
    public AjaxResult doBossException(BossException bossException) {

        //获取响应码
        ResponseCode responseCode = bossException.getResponseCode();

        logger.error("发生了BossException 相应码为：{}，异常的信息为{}", responseCode.getNumber(), responseCode.getMsg());
        return AjaxResult.fail(responseCode);

    }


    //处理Bean Validation异常
    @ExceptionHandler(BindException.class)
    public AjaxResult doBeanValidation(BindException bindException) {
        BindingResult bindingResult = bindException.getBindingResult();
        List<FieldError> fieldErrors = bindingResult.getFieldErrors();


        StringBuffer stringBuffer = new StringBuffer();
        fieldErrors.forEach(fieldError -> {
           /* stringBuffer.append("您的错误项为【").append(fieldError.getField()).append("】，原因是 【").append(fieldError.getDefaultMessage()).append("】");*/
            stringBuffer.append("您的错误项为【")
                    .append(fieldError.getDefaultMessage())
                    .append("】;");
        });

        AjaxResult ajaxResult = new AjaxResult();
        ajaxResult.setCode(ResponseCode.REQUEST_PARMA_ERR.getNumber());
        ajaxResult.setMsg(ResponseCode.REQUEST_PARMA_ERR.getMsg() + "|原因" + stringBuffer.toString());
        ajaxResult.setData("");


        return ajaxResult;

    }

}
